#!/bin/sh
### BEGIN INIT INFO
# Provides:          gateway-iptables
# Required-Start:    $all
# Required-Stop:
# Default-Start:     3 4 5
# Default-Stop:
# Short-Description: Redirect :80 to :8080 and :443 to :4443
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin

. /lib/init/vars.sh
. /lib/lsb/init-functions

do_start() {
  [ "$VERBOSE" != no ] && log_begin_msg "Redirecting :80 to :8080 and :443 to :4443"
  iptables -t mangle -A PREROUTING -p tcp --dport 80 -j MARK --set-mark 1
  iptables -t mangle -A PREROUTING -p tcp --dport 443 -j MARK --set-mark 1
  iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
  iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 4443
  iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -m mark --mark 1 -j ACCEPT
  iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 4443 -m mark --mark 1 -j ACCEPT
  ES=$?
  [ "$VERBOSE" != no ] && log_end_msg $ES
  return $ES
}

case "$1" in
    start)
        do_start
        ;;
    restart|reload|force-reload)
        echo "Error: argument '$1' not supported" >&2
        exit 3
        ;;
    stop|status)
        # No-op
        exit 0
        ;;
    *)
        echo "Usage: $0 start|stop" >&2
        exit 3
        ;;
esac
